package com.java.multipledatasource.thread;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author hu
 * @version 1.0
 * @date 2021/1/16 0016 下午 7:01
 * @description 实现一个容器 一个线程 添加10个元素，另一个线程 监控当添加到第5个元素的时候停止添加
 */
public class Thread2_2 {

    List list = Collections.synchronizedList(new ArrayList<>(10));

    private void add (Object o) {
        this.list.add(o);
    }

    private int size() {
        return  this.list.size();
    }

    public static void main(String[] args) {
        Thread2_2 t = new Thread2_2();
        final  Object obj = new Object();
        new Thread(() -> {
            System.out.println("t2 start");
            synchronized (obj) {
                if (t.size() != 5) {
                    try {
                        obj.wait(); // wait 回家必须拿到锁 才可以继续执行
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                System.out.println("t2 end");
                obj.notify();
            }

        }, "t2").start();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(() -> {
            System.out.println("t1 start");

            synchronized (obj) {
                for (int i = 0; i < 10; i++) {
                    System.out.println(i);
                    t.add(obj);

                    if (t.size() == 5) {
                       obj.notify(); // notity 不释放锁

                        try {
                            obj.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

        }, "t1").start();
    }
}
